import "package:share_image_server/export_all.dart";

//
// auth: Du Long
// date: 2024-09-15
// description:
//

//控制器消息记录
final infoMiddleware = createMiddleware(
  requestHandler: (request) {
    logI("进入记录控制器...");
    logI("request开始时间:${DateTime.now()}");
    var watch = Stopwatch()..start();
    logI("===request_start===");
    logI("请求路径:${request.requestedUri}");
    logI("请求参数${request.url.queryParametersAll}");
    logI("请求方法:${request.method}");
    logI("请求头:${request.headersAll}");
    logI("===request_end===");
    logI("request结束时间:${DateTime.now()}");
    logI("request耗时:${watch.elapsed}");
    return null;
  },
  responseHandler: (response) {
    logI("response开始时间:${DateTime.now()}");
    var watch = Stopwatch()..start();
    logI("===response_start===");
    logI("响应头:${response.headersAll}");
    logI("响应状态码:${response.statusCode}");
    logI("结束时间:${DateTime.now()}");
    logI("耗时:${watch.elapsed}");
    logI("===response_end===");
    // 处理响应
    logI("response结束时间:${DateTime.now()}");
    logI("response耗时:${watch.elapsed}");
    logI("离开记录控制器...");
    return response;
  },
  errorHandler: (error, stackTrace) {
    logE(error.toString());
    logE(stackTrace.toString());
    ResponseApi responseApi = ResponseApi(
        code: 500, msg: "服务器异常,错误已被记录", dataType: "String", data: "");
    return Response(responseApi.code, body: responseApiToJson(responseApi))
        .change(headers: {"content-type": "application/json"});
  },
);

//过滤器
final filterMiddleware = createMiddleware(
  requestHandler: (request) async {
    return null;
  },
  responseHandler: (response) async {
    Map<String, String> headerCORS = {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers": "Content-Type, Authorization",
      "Access-Control-Allow-Methods": "GET, POST",
      "Access-Control-Allow-Credentials": "false",
    };
    return response.change(headers: headerCORS);
  },
  errorHandler: (error, stackTrace) async {
    logE(error.toString());
    logE(stackTrace.toString());
    ResponseApi responseApi = ResponseApi(
        code: 500, msg: "服务器异常,错误已被记录", dataType: "String", data: "");
    return Response(responseApi.code, body: responseApiToJson(responseApi))
        .change(headers: {"content-type": "application/json"});
  },
);

//拦截器
Middleware interceptor() => (innerHandler) {
      return (request) async {
        if (request.requestedUri.path == "/upload" &&
            request.method == "POST") {
          String token = request.headers["Authorization"].toString();
          if (token.isEmpty) {
            ResponseApi responseApi = ResponseApi(
                code: 403,
                msg: "你的请求是不被允许的,缺少请求头",
                dataType: "String",
                data: "");
            return Response(responseApi.code,
                    body: responseApiToJson(responseApi))
                .change(headers: {"content-type": "application/json"});
          }
          if (!await cT(token)) {
            ResponseApi responseApi = ResponseApi(
                code: 403,
                msg: "认证不合格",
                dataType: "String",
                data: "");
            return Response(responseApi.code,
                    body: responseApiToJson(responseApi))
                .change(headers: {"content-type": "application/json"});
          }
        }

        return Future.sync(() => innerHandler(request)).then((response) async {
          if (response.headers["content-type"] == null) {
            ResponseApi responseApi = ResponseApi(
                code: 500,
                msg: "未知错误",
                dataType: "String",
                data: await response.readAsString());
            return Response(responseApi.code,
                    body: responseApiToJson(responseApi))
                .change(headers: {"content-type": "application/json"});
          }
          return response;
        }, onError: (Object error, StackTrace stackTrace) async {
          if (error is HijackException) {
            logE(error.toString());
            ResponseApi responseApi = ResponseApi(
                code: 500, msg: "服务器异常,错误已被记录", dataType: "String", data: "");
            return Response(responseApi.code,
                    body: responseApiToJson(responseApi))
                .change(headers: {"content-type": "application/json"});
          }
          logE(request.requestedUri.toString());
          logE(request.method);
          logE(error.toString());
          logE(stackTrace.toString());
          logE(error.toString());
          logE(stackTrace.toString());
          ResponseApi responseApi = ResponseApi(
              code: 500, msg: "服务器异常,错误已被记录", dataType: "String", data: "");
          return Response(responseApi.code,
                  body: responseApiToJson(responseApi))
              .change(headers: {"content-type": "application/json"});
        });
      };
    };
